//
//  BaiduMapViewController.mm
//  WisdomZhuHai
//
//  Created by Ryan on 15-1-29.
//  Copyright (c) 2015年 wyd. All rights reserved.
//

#import "BaiduMapViewController.h"
#import "TransforController.h"
#import "UIImage+Rotate.h"
#import "BaiduRouteTableViewController.h"

#define MYBUNDLE_NAME @ "mapapi.bundle"
#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
#define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]

@interface BaiduMapViewController () <beginToNavDelegate>
{
    BMKPointAnnotation *pointAnnotation;
    BMKAnnotationView *newAnnotation;
    
    BMKLocationService *_locService;
    BMKRouteSearch *_routesearch;
}

@property (nonatomic, strong)NSString* latitude;
@property (nonatomic, strong)NSString* longitude;
@property (nonatomic, assign)NSInteger index;
@property (nonatomic, assign)BOOL getBackToNav;
@property (nonatomic, strong)BMKTransitRouteLine* busLine;
@property (nonatomic, strong)BMKDrivingRouteLine* driverLine;
@property (nonatomic, strong)BMKTransitRouteResult* busResult;
@property (nonatomic, strong)BMKDrivingRouteResult* driverResult;

@end

@interface RouteAnnotation : BMKPointAnnotation
{
    int _type; ///<0:起点 1：终点 2：公交 3：地铁 4:驾乘 5:途经点
    int _degree;
}

@property (nonatomic) int type;
@property (nonatomic) int degree;
@end

@implementation RouteAnnotation

@synthesize type = _type;
@synthesize degree = _degree;
@end


@implementation BaiduMapViewController

- (NSString*)getMyBundlePath1:(NSString *)filename
{
    
    NSBundle * libBundle = MYBUNDLE ;
    if ( libBundle && filename ){
        NSString * s=[[libBundle resourcePath ] stringByAppendingPathComponent : filename];
        return s;
    }
    return nil ;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    UIView *localbtnView = [[UIView alloc] initWithFrame:CGRectMake(260, [UIScreen mainScreen].bounds.size.height - 130, 50, 50)];
    localbtnView.backgroundColor = [UIColor clearColor];
    UIImageView *localbtnImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"nav_route_map_location"]];
    UITapGestureRecognizer *onTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(startFollowing:)];
    [localbtnView addSubview:localbtnImg];
    [localbtnView addGestureRecognizer:onTap];
    _mapView = [[[BMKMapView alloc] initWithFrame:CGRectMake(0, 65, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 100)] autorelease];
    _mapView.delegate = self;
    _locService = [[BMKLocationService alloc] init];
    _locService.delegate = self;
    _routesearch = [[BMKRouteSearch alloc]init];
    _routesearch.delegate = self;
    [self.view addSubview:[TransforController shardeInstanceOfNavigationBarAndStatusBarCoverViewWithY:0 andTitle:@"路线规划"]];
    [self.view addSubview:_mapView];
    [self.view addSubview:localbtnView];
    [self tabbarSetup];
    
    [self locationViewDisplay];
    [self startLocation];
    self.getBackToNav = NO;
    if (pointAnnotation == nil) {
        [self jumpToPlace];
        [self addPointAnnotation];
    }
}

- (void)mapViewSetup {
    //地图类型
    _mapView.mapType = BMKMapTypeStandard;
    //指南针位置
    _mapView.compassPosition = CGPointMake(10, 100);
    //多点缩放
    _mapView.zoomEnabled = TRUE;
    //中心点缩放和旋转
    _mapView.ChangeWithTouchPointCenterEnabled = TRUE;
    //
}

- (void)jumpToPlace {
    NSLog(@"%s",__FUNCTION__);
    CLLocationCoordinate2D coor;
    //把gps字符串转正float
    NSString *gps = _gps;
    if ([gps isEqualToString:@""] || gps.length <= 0) {
        return;
    }
    NSArray *gpsArray = [gps componentsSeparatedByString:@","];
    coor.longitude = [gpsArray[0] floatValue];
    coor.latitude = [gpsArray[1]floatValue];
    
    BMKMapStatus *mapStatus = [[BMKMapStatus alloc] init];
    mapStatus.fLevel = 13;
    
    //设置地理坐标
    mapStatus.targetGeoPt = CLLocationCoordinate2DMake(coor.latitude, coor.longitude);
    //动画
    [_mapView setMapStatus:mapStatus withAnimation:YES];
    [mapStatus release];
}

- (void)addPointAnnotation {
    pointAnnotation = [[BMKPointAnnotation alloc] init];
    CLLocationCoordinate2D coor;
    NSString *gps = _gps;
    if ([gps isEqualToString:@""] || gps.length <= 0) {
        return;
    }
    NSArray *gpsArray = [gps componentsSeparatedByString:@","];
    coor.longitude = [gpsArray[0] floatValue];
    coor.latitude = [gpsArray[1]floatValue];
    
    
    pointAnnotation.coordinate = coor;
    pointAnnotation.title = _name;
//    pointAnnotation.subtitle = @"此处可以拖拽";
    [_mapView addAnnotation:pointAnnotation];
    [pointAnnotation release];
}

//根据anntation生成对应的view
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation {
    NSString *AnnotationViewID = @"renameMark";
    if (newAnnotation == nil) {
        newAnnotation = [[[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID] autorelease];
        //设置颜色
//        ((BMKPinAnnotationView*)newAnnotation).pinColor = BMKPinAnnotationColorPurple;
        UIView *viewForImage=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 70)];
        UIImageView *imageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 70)];
        [imageview setImage:[UIImage imageNamed:@"mapapi.bundle/images/icon_nav_end"]];
        [viewForImage addSubview:imageview];
         newAnnotation.image=[self getImageFromView:viewForImage];
    }
    if ([annotation isKindOfClass:[RouteAnnotation class]]) {
        return [self getRouteAnnotationView:mapView viewForAnnotation:(RouteAnnotation*)annotation];
    }
    return newAnnotation;
}

- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay
{
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:1];
        polylineView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.7];
        polylineView.lineWidth = 3.0;
        return polylineView;
    }
    return nil;
}

- (BMKAnnotationView*)getRouteAnnotationView:(BMKMapView *)mapview viewForAnnotation:(RouteAnnotation*)routeAnnotation
{
    BMKAnnotationView* view = nil;
    switch (routeAnnotation.type) {
        case 0:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"start_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"start_node"];
                view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_start.png"]];
                view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        }
            break;
        case 1:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"end_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"end_node"];
                view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_end.png"]];
                view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        }
            break;
        case 2:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"bus_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"bus_node"];
                view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_bus.png"]];
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        }
            break;
        case 3:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"rail_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"rail_node"];
                view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_rail.png"]];
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        }
            break;
        case 4:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"route_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"route_node"];
                view.canShowCallout = TRUE;
            } else {
                [view setNeedsDisplay];
            }
            
            UIImage* image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_direction.png"]];
            view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
            view.annotation = routeAnnotation;
            
        }
            break;
        case 5:
        {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"waypoint_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"waypoint_node"];
                view.canShowCallout = TRUE;
            } else {
                [view setNeedsDisplay];
            }
            
            UIImage* image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_waypoint.png"]];
            view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
            view.annotation = routeAnnotation;
        }
            break;
        default:
            break;
    }
    
    return view;
}

-(UIImage *)getImageFromView:(UIView *)view{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (void)locationViewDisplay {
    BMKLocationViewDisplayParam *localParam = [[BMKLocationViewDisplayParam alloc] init];
    localParam.isRotateAngleValid = YES;
    localParam.isAccuracyCircleShow = NO;
//    localParam.locationViewImgName = @"icon_compass";
    localParam.locationViewOffsetX = 0;
    localParam.locationViewOffsetY = 0;
    [_mapView updateLocationViewWithParam:localParam];
    [localParam release];
}

- (void)tabbarSetup {
    UIView *tabbarView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 60, 320, 60)];
    tabbarView.backgroundColor = [Common colorWithRGB:0xf9f9f9];
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 1)];
    line.backgroundColor = [Common colorWithRGB:0xb2b2b2];
    [tabbarView addSubview:line];
    
    UIView *firstView = [[UIView alloc] initWithFrame:CGRectMake(43, 5, 40, 50)];
    firstView.backgroundColor = [UIColor clearColor];
    UIImageView *firstImageView = [[UIImageView alloc] initWithFrame:CGRectMake(2.5, 2.5, firstView.bounds.size.width - 5, firstView.bounds.size.width - 5)];
    firstImageView.image = [UIImage imageNamed:@"map/nav_route_bus"];
    UILabel *firstLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, firstView.bounds.size.width, 10)];
    firstLab.textAlignment = UITextAlignmentCenter;
    firstLab.textColor = [Common colorWithRGB:0xb2b2b2];
    firstLab.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:12.0];
    firstLab.text = @"公交";
    firstView.tag = 40001;
    UITapGestureRecognizer *onFirstTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickBusSearch:)] autorelease];
    [firstView addSubview:firstImageView];
    [firstView addSubview:firstLab];
    [firstView addGestureRecognizer:onFirstTap];
    
    UIView *secondView = [[UIView alloc] initWithFrame:CGRectMake(140, 5, 40, 50)];
    secondView.backgroundColor = [UIColor clearColor];
    UIImageView *secondImageView = [[UIImageView alloc] initWithFrame:CGRectMake(2.5, 2.5, secondView.bounds.size.width - 5, secondView.bounds.size.width - 5)];
    secondImageView.image = [UIImage imageNamed:@"map/nav_route_car"];
    UILabel *secondLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, secondView.bounds.size.width, 10)];
    secondLab.textAlignment = UITextAlignmentCenter;
    secondLab.textColor = [Common colorWithRGB:0xb2b2b2];
    secondLab.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:12.0];
    secondLab.text = @"驾车";
    secondView.tag = 40002;
    UITapGestureRecognizer *onSecondTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickDriveSearch:)] autorelease];
    [secondView addSubview:secondImageView];
    [secondView addSubview:secondLab];
    [secondView addGestureRecognizer:onSecondTap];
    
    UIView *thirdView = [[UIView alloc] initWithFrame:CGRectMake(235, 5, 40, 50)];
    thirdView.backgroundColor = [UIColor clearColor];
    UIImageView *thirdImageView = [[UIImageView alloc] initWithFrame:CGRectMake(2.5, 2.5, thirdView.bounds.size.width - 5, thirdView.bounds.size.width - 5)];
    thirdImageView.image = [UIImage imageNamed:@"map/nav_route_walk"];
    UILabel *thirdLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, thirdView.bounds.size.width, 10)];
    thirdLab.textAlignment = UITextAlignmentCenter;
    thirdLab.textColor = [Common colorWithRGB:0xb2b2b2];
    thirdLab.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:13.0];
    thirdLab.text = @"步行";
    thirdView.tag = 40003;
    UITapGestureRecognizer *onThirdTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickWalkSearch:)] autorelease];
    [thirdView addSubview:thirdImageView];
    [thirdView addSubview:thirdLab];
    [thirdView addGestureRecognizer:onThirdTap];
    
    
    [tabbarView addSubview:firstView];
    [tabbarView addSubview:secondView];
    [tabbarView addSubview:thirdView];
    [self.view addSubview:tabbarView];
}

- (void)startLocation {
    NSLog(@"进入普通定位");
    [_locService startUserLocationService];
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeNone;
    _mapView.showsUserLocation = YES;
}

//跟随态
-(void)startFollowing:(UITapGestureRecognizer *)onTap
{
    NSLog(@"进入跟随态");
//    [_locService startUserLocationService];
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
    _mapView.showsUserLocation = YES;
    
}

//tabbar点击事件
- (void)onClickBusSearch:(UITapGestureRecognizer*)onTap
{
    NSString *gps = _gps;
    if ([gps isEqualToString:@""] || gps.length <= 0) {
        return;
    }
    NSArray *gpsArray = [gps componentsSeparatedByString:@","];
    BMKPlanNode *start = [[[BMKPlanNode alloc] init] autorelease];
    CLLocationCoordinate2D coor;
    coor.latitude = [_latitude floatValue];
    coor.longitude = [_longitude floatValue];
    start.pt = coor;
//    start.name = @"北师大";
    BMKPlanNode *end = [[[BMKPlanNode alloc] init] autorelease];
    coor.latitude = [gpsArray[1] floatValue];
    coor.longitude = [gpsArray[0] floatValue];
    end.pt = coor;
//    end.name = @"圆明新园";
    //公交路线检索
    BMKTransitRoutePlanOption *transitRouteSearchOption = [[BMKTransitRoutePlanOption alloc]init];
    transitRouteSearchOption.city= @"珠海市";
    transitRouteSearchOption.from = start;
    transitRouteSearchOption.to = end;
    transitRouteSearchOption.transitPolicy = BMK_TRANSIT_TIME_FIRST;
    BOOL flag = [_routesearch transitSearch:transitRouteSearchOption];
    
    if(flag)
    {
        NSLog(@"bus检索发送成功");
    }
    else
    {
        NSLog(@"bus检索发送失败");
    }
}

-(IBAction)onClickDriveSearch:(UITapGestureRecognizer*)onTap
{
    NSString *gps = _gps;
    if ([gps isEqualToString:@""] || gps.length <= 0) {
        return;
    }
    NSArray *gpsArray = [gps componentsSeparatedByString:@","];
    BMKPlanNode *start = [[[BMKPlanNode alloc] init] autorelease];
    CLLocationCoordinate2D coor;
    coor.latitude = [_latitude floatValue];
    coor.longitude = [_longitude floatValue];
    start.pt = coor;
    start.cityName = @"珠海市";
    //    start.name = @"北师大";
    BMKPlanNode *end = [[[BMKPlanNode alloc] init] autorelease];
    coor.latitude = [gpsArray[1] floatValue];
    coor.longitude = [gpsArray[0] floatValue];
    end.pt = coor;
    end.cityName = @"珠海市";
    
    BMKDrivingRoutePlanOption *drivingRouteSearchOption = [[BMKDrivingRoutePlanOption alloc]init];
    drivingRouteSearchOption.from = start;
    drivingRouteSearchOption.to = end;
    drivingRouteSearchOption.drivingPolicy = BMK_DRIVING_TIME_FIRST;
    BOOL flag = [_routesearch drivingSearch:drivingRouteSearchOption];
    if(flag)
    {
        NSLog(@"car检索发送成功");
    }
    else
    {
        NSLog(@"car检索发送失败");
    }
    
}

-(IBAction)onClickWalkSearch:(UITapGestureRecognizer*)onTap
{
    
    NSString *gps = _gps;
    if ([gps isEqualToString:@""] || gps.length <= 0) {
        return;
    }
    NSArray *gpsArray = [gps componentsSeparatedByString:@","];
    BMKPlanNode *start = [[[BMKPlanNode alloc] init] autorelease];
    CLLocationCoordinate2D coor;
    coor.latitude = [_latitude floatValue];
    coor.longitude = [_longitude floatValue];
    start.pt = coor;
    start.cityName = @"珠海市";
    //    start.name = @"北师大";
    BMKPlanNode *end = [[[BMKPlanNode alloc] init] autorelease];
    coor.latitude = [gpsArray[1] floatValue];
    coor.longitude = [gpsArray[0] floatValue];
    end.pt = coor;
    end.cityName = @"珠海市";
    
    BMKWalkingRoutePlanOption *walkingRouteSearchOption = [[BMKWalkingRoutePlanOption alloc]init];
    walkingRouteSearchOption.from = start;
    walkingRouteSearchOption.to = end;
    BOOL flag = [_routesearch walkingSearch:walkingRouteSearchOption];
    if(flag)
    {
        NSLog(@"walk检索发送成功");
    }
    else
    {
        NSLog(@"walk检索发送失败");
    }
    
}

- (void)goToLineCtrl:(BOOL)is_bus
{
    BaiduRouteTableViewController *routeCellCtrl = [[BaiduRouteTableViewController alloc] init];
    if (is_bus) {
        routeCellCtrl.busResult = _busResult;
        routeCellCtrl.is_bus = YES;
    } else {
        routeCellCtrl.driverResult = _driverResult;
        routeCellCtrl.is_bus = NO;
    }
    routeCellCtrl.mapNavDelegate = self;
    routeCellCtrl.name = [NSString stringWithFormat:@"%@",_name];
    [self.navigationController pushViewController:routeCellCtrl animated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    [self jumpToPlace];
    self.getBackToNav = NO;
    self.index = 0;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)didMoveToParentViewController:(UIViewController *)parent {
    if (parent == nil) {
        [_locService stopUserLocationService];
        [_mapView removeFromSuperview];
        _mapView = nil;
        _mapView.delegate = nil;
        _locService = nil;
        _routesearch = nil;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
- (void)willStartLocatingUser
{
    NSLog(@"start locate");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
//    NSLog(@"heading is %@",userLocation.heading);
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
//        NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    self.latitude = [NSString stringWithFormat:@"%f", userLocation.location.coordinate.latitude ];
    self.longitude = [NSString stringWithFormat:@"%f", userLocation.location.coordinate.longitude ];
//    self.latitude = [NSString stringWithFormat:@"%f", 22.361178 ];
//    self.longitude = [NSString stringWithFormat:@"%f", 113.551331 ];
    [_mapView updateLocationData:userLocation];
}

/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser
{
    NSLog(@"stop locate");
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error %@",error);
}

//获取公交规划结果
- (void)onGetTransitRouteResult:(BMKRouteSearch*)searcher result:(BMKTransitRouteResult*)result errorCode:(BMKSearchErrorCode)error
{
    NSLog(@" %@ , %@ , %u",searcher , result, error);
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        self.busResult = result;
        if (_getBackToNav ==  NO) {
            [self goToLineCtrl:YES];
        }
        BMKTransitRouteLine* plan = (BMKTransitRouteLine*)[result.routes objectAtIndex:_index];
        // 计算路线方案中的路段数目
        int size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKTransitStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                item.title = @"我的位置";
                item.type = 0;
                [_mapView addAnnotation:item]; // 添加起点标注
                
            }else if(i==size-1){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = _name;
                item.type = 1;
                [_mapView addAnnotation:item]; // 添加起点标注
            }
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
            item.title = transitStep.instruction;
            item.type = 2;
            [_mapView addAnnotation:item];
            
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
            
            NSLog(@"%@",transitStep.instruction);
        }
        
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKTransitStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
            
        }
        // 通过points构建BMKPolyline
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_mapView addOverlay:polyLine]; // 添加路线overlay
        delete []temppoints;
    }
}

- (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        self.driverResult = result;
        if (_getBackToNav ==  NO) {
            [self goToLineCtrl:NO];
        }
        BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:_index];
        // 计算路线方案中的路段数目
        int size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                item.title = @"我的位置";
                item.type = 0;
                [_mapView addAnnotation:item]; // 添加起点标注
                
            }else if(i==size-1){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = _name;
                item.type = 1;
                [_mapView addAnnotation:item]; // 添加起点标注
            }
            //添加annotation节点
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
            item.title = transitStep.entraceInstruction;
            item.degree = transitStep.direction * 30;
            item.type = 4;
            [_mapView addAnnotation:item];
            
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        // 添加途经点
        if (plan.wayPoints) {
            for (BMKPlanNode* tempNode in plan.wayPoints) {
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item = [[RouteAnnotation alloc]init];
                item.coordinate = tempNode.pt;
                item.type = 5;
                item.title = tempNode.name;
                [_mapView addAnnotation:item];
            }
        }
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
            
        }
        // 通过points构建BMKPolyline
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_mapView addOverlay:polyLine]; // 添加路线overlay
        delete []temppoints;
        
        
    }
}

- (void)onGetWalkingRouteResult:(BMKRouteSearch*)searcher result:(BMKWalkingRouteResult*)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        BMKWalkingRouteLine* plan = (BMKWalkingRouteLine*)[result.routes objectAtIndex:0];
        int size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKWalkingStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                item.title = @"我的位置";
                item.type = 0;
                [_mapView addAnnotation:item]; // 添加起点标注
                
            }else if(i==size-1){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = _name;
                item.type = 1;
                [_mapView addAnnotation:item]; // 添加起点标注
            }
            //添加annotation节点
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
            item.title = transitStep.entraceInstruction;
            item.degree = transitStep.direction * 30;
            item.type = 4;
            [_mapView addAnnotation:item];
            
            //轨迹点总数累计
            planPointCounts += transitStep.pointsCount;
        }
        
        //轨迹点
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKWalkingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
            
        }
        // 通过points构建BMKPolyline
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_mapView addOverlay:polyLine]; // 添加路线overlay
        delete []temppoints;
        
        
    }
    
}

- (void)beginToNav:(NSInteger)index busResult:(BMKTransitRouteResult*)busResult carResult:(BMKDrivingRouteResult*)carResult {
    NSLog(@"%s,index%d", __FUNCTION__, index);
    self.index = index;
    self.getBackToNav = YES;
    if (busResult == nil) {
        [self onGetDrivingRouteResult:nil result:carResult errorCode:BMK_SEARCH_NO_ERROR];
    } else {
        [self onGetTransitRouteResult:nil result:busResult errorCode:BMK_SEARCH_NO_ERROR];
    }
    
}

@end
